(function ( $ ) {
 
    $.fn.ccapitalzr = function( options ) {
 
        var settings = $.extend({
            weather: true,
            map: true,
			tweets: true,
			mashapeKey: 'EllcuGT8dFmsh4hM0KfDR4am8Dcop1pneWUjsn7cyFj3VMIqza',
			googleKey: 'AIzaSyCINGFOT7LZCycK5WHPDsVlQisz5R9S1XA',
			tweetsApi: 'https://api.twitter.com/1.1/trends/place.json?id=',
			woeKey: 'z5tLmV7V34FUqOq81t2Z5MzUvvVSVLG_C6s3p8.0xfh5t4LcTum7azXtwBQCYr.vkwE-'
        }, options );
		
		var select = this;
		var holder = $('<div></div>');
		var locationMap = {};
		var selectxt = 'Select Country'
		
		if(select.is('select'))
		{
			$.ajax({
			     url: 'https://restcountries-v1.p.mashape.com/all',
				 beforeSend: function(request) { 
					request.setRequestHeader("X-Mashape-Key", settings.mashapeKey); 
					select.html('<option>Please wait..</option');
				}
			 }).then(function(data) {
				 select.html('<option>'+selectxt+'</option');
				 $.each(data, function (i, country) {
					if(country.capital != '')
				    	select.append('<option value="' + country.capital + '">' + country.name  + '</option>');
					/*
					if(settings.map)
					{
						locationMap[country.capital] = country.latlng;
					}
					*/
				});
			 });
			
			if(settings.map || settings.weather || settings.tweets)
				select.after(holder);
			
			select.on('change', function() {
				
				holder.children().remove();
				
				var capital = select.val();
				
				if(capital === selectxt) return;
				
				holder.append(
					'<p id="capital"></p>' +
					(settings.weather ? '<div id="weather"></div>' : '') +
					(settings.map ? '<div id="map"></div>' : '') +
					(settings.tweets ? '<div id="tweets"></div>' : '')
				);
					
				$('#capital').html('<b>Capital:</b> ' + capital);
				
				if(capital.indexOf("'")) capital = capital.replace(/'/g, "");
				
				capital = encodeURIComponent(capital);
				
				displayWeather(capital);
				
				//restcountries.eu coordinates are inaccurate.. using openweathermap.org
				$.ajax({
				     url: 'http://api.openweathermap.org/data/2.5/weather?q=' + capital
				 }).then(function(data) {
					var latlng = [data.coord.lat, data.coord.lon];
					displayMap(latlng);
				 });
				//displayTweets(capital); client-side oauth not working
			});
		}
		
		
		var displayWeather = function(capital){
			
			if(!settings.weather) return;
			
			var div = $('#weather');
			$.ajax({
			     url: 'http://api.openweathermap.org/data/2.5/weather?q=' + capital,
				 beforeSend: function(request) { 
					div.html('Fetching weather info..');
				}
			 }).then(function(data) {
				div.html('');
				var desc = "";
				for(var i in data.weather)
				{
					desc += data.weather[i].description + (data.weather[i+1] ? ', ' : '');
				}
				var temp = new Number(data.main.temp - 273.15);
				temp = temp.toPrecision(2);
				
				
				div.append(
					'<p><b>Weather:</b> ' + desc + 
					', with a temperature of ' + temp + ' &degC' +
					' and ' + data.main.humidity + '% humidity.</p>'
				);
			 });
			holder.append(div);
		}
		
		var displayMap = function(latlng) {
			if(!settings.map) return;
			
			var mapOptions = {
			    zoom: 8,
			    center: new google.maps.LatLng(latlng[0], latlng[1])
			 }
			
			var div = document.getElementById('map');
			$(div).css({ width: '400px', height: '200px'});
			map = new google.maps.Map(div, mapOptions);
			holder.append(div);
		}
		
		var displayTweets = function(capital) {
			if(!settings.tweets) return;
			
			$.ajax({ 
				url: 'http://where.yahooapis.com/v1/places.q('+capital+')?format=json&appid=' + settings.woeKey 
			}).then(function(data) {
				var woeId = data.places.place[0].woeid;
				var twt = 'https://api.twitter.com/1.1/trends/place.json?id=' + woeId;
				var div = $('#tweets');

				//client-side oauth (not recommended)
				consumerKey = "D3ZclGkrF6qLe6kZ71AfMk6kD";
				consumerSecret = "Bbqh3zox7CbBTheZqcfEWUZHoeWUcfhcE2JNlAjwXoWa1i2f3l";
			    accessToken = "261045145-FhiZUAZa4vc99j5nSTMekvyhidLCG2a49sW40dLs";
			    accessTokenSecret = "kS4dievhL8usaxAqaT58hZki6O7NHfD6iPUYXfgzIalql";
			
				var sig = createOAuthSig(consumerKey, consumerSecret, accessToken, accessTokenSecret);
			    
				var nonce = OAuth.nonce(32);
			    var ts = Math.floor(new Date().getTime() / 1000);
			    var timestamp = ts.toString();
			
				$.ajax({
					type: 'GET',
					headers: {
			            "Authorization": "OAuth", 
						"oauth_consumer_key": consumerKey,
						"oauth_nonce": nonce,
						"oauth_signature": sig, 
						"oauth_signature_method": "HMAC-SHA1", 
						"oauth_timestamp": timestamp,
						"oauth_token=": accessToken, 
						"oauth_version": "1.0"
			        },
					url: twt,
					success: function(data){
					}
				});
				
			});
			
			
		}
    };
 
}( jQuery ));